
<!-- 低代码 主页面：用于展示多表单多表格类型的详情页  eui-page-frame-->

<template>
	<eui-background type="common" :mainWrapClass="props?.parentType !== 'approveManger' ? '' : 'lowcode-approve-wrap'" :style="state.approveStyle || ''" :commainStyle="state.approveStyle || ''">
    <view class="lowcode-nav-bg-wrap">
			<eui-nav-bar :title="getNavTitle()" color="#FFF"  />
		</view>
		<eui-card :title="getMainCardTitle()" hPadding="28" type="single">
			<template v-if="state?.mainFormData?.c_status" v-slot:extra><view class="extra-view" style="position: absolute;right: 0;top: -2rpx;">
				<view :class="'lowcode-part-bezier '+getMainStatusType()" ><view class="lowcode-quarter-circle"/></view>
				<eui-status :type="getMainStatusType()" :title="EBillStatusTxt[state?.mainFormData?.c_status]" style="border-radius: 0 20rpx 0 26rpx" />
			</view></template>
			<view class="lowcode-page-card-cnt-wrap" :style="state.mainCardStyle">
				<view class="lowcode-page-card-cnt">
					<eui-row v-for="(rowCols, fIdx) in state?.mainFormPanelGrid?.Components" :key="fIdx" class="lowcode-page-row-wrap">
						<eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
							<eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%" v-bind="state.mainCellProps?.['main_'+fIdx+'_'+cfIdx]" />
							<UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true" :autoUpload="false" prefix="mainApi" serviceName="EnjoyMain" fileMediatype="image" :fileId="state?.mainFormData?.[colField.c_code || '']" fileClass="lowcode"
								return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }" :customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY" customFetchMethodName="FetchLowcodeFile" />
						</eui-col>
					</eui-row>
				</view>
				<view class="lowcode-page-sub-card-panel" v-for="(mainSubCardFormPanel, pIdx) in getMainSubCardFormPanels()">
					<view class="lowcode-page-sub-card-chead-wrap" v-if="mainSubCardFormPanel?.c_name" >
						<text class="lowcode-card-title item-text item-text-detail">{{ mainSubCardFormPanel?.c_name }}</text>
					</view>
					<view class="lowcode-title-line" v-if="mainSubCardFormPanel?.c_name" />
					<view class="lowcode-page-sub-card-cnt" v-if="mainSubCardFormPanel?.Components?.length">
						<eui-row v-for="(rowCols, fIdx) in mainSubCardFormPanel?.Components" :key="fIdx" class="lowcode-page-row-wrap">
							<eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
								<eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%" v-bind="state.subCellProps?.['main_sub'+(mainSubCardFormPanel?.c_guid || '')+fIdx+'_'+cfIdx]" />
								<UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true" :autoUpload="false" prefix="mainApi" serviceName="EnjoyMain" fileMediatype="image" :fileId="state?.mainFormData?.[colField.c_code || '']" fileClass="lowcode"
									return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }" :customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY" customFetchMethodName="FetchLowcodeFile" />
							</eui-col>
						</eui-row>
					</view>
				</view>
			</view>
		</eui-card>
		<view class="lowcode-list-view" :style="props?.parentType !== 'approveManger' ? 'margin-bottom: 112rpx;' : ''" v-if="Object.keys(state?.otherPanelGridObj || {})?.length">
			<view v-for="(oPanelGridGuid, pIdx) in Object.keys(state.otherPanelGridObj || {})" :key="pIdx" class="lowcode-rich-o-panel-grid-wrap">
				<eui-card v-if="(state?.otherPanelGridObj?.[oPanelGridGuid]?.c_type === '3' && state.otherCellPropsAny?.[oPanelGridGuid] && state?.otherPanelGridObj?.[oPanelGridGuid]?.Components?.length)" :title="state?.otherPanelGridObj?.[oPanelGridGuid]?.c_name" hPadding="28" type="single" >
					<view class="lowcode-title-line" />
					<view  v-for="(rowData, idx) in (state.otherPanelData?.[oPanelGridGuid])" :key="idx" class="lowcode-edit-page-tb-row-wrap" >
						<view class="lowcode-edit-page-tb-row-title">第{{ (+idx || 0) + 1 }}行</view>
						<view class="lowcode-page-card-chead-wrap" v-if="state?.otherPanelGridObj?.[oPanelGridGuid]?.ComponentsHeade?.length" >
							<eui-row v-for="(rowCols, fIdx) in state?.otherPanelGridObj?.[oPanelGridGuid]?.ComponentsHeade" :key="fIdx" class="lowcode-page-row-wrap">
								<eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
									<view class="lowcode-item-detail-view" >
										<text class="lowcode-card-title item-text item-text-detail">{{ getDetailCardTitle(rowData, colField) }}</text>
									</view>
								</eui-col>
							</eui-row>
						</view>
						<view class="lowcode-title-line" v-if="state?.otherPanelGridObj?.[oPanelGridGuid]?.ComponentsHeade?.length" />
						<view class="lowcode-page-card-cnt" v-if="state?.otherPanelGridObj?.[oPanelGridGuid]?.Components?.length">
							<eui-row v-for="(rowCols, fIdx) in state?.otherPanelGridObj?.[oPanelGridGuid]?.Components" :key="fIdx" class="lowcode-page-row-wrap">
								<eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
									<eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%" v-bind="state.otherCellProps?.[oPanelGridGuid+'_'+idx+'_'+fIdx+'_'+cfIdx]" />
									<UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true" :autoUpload="false" serviceName="EnjoyMain" fileMediatype="image" :fileId="rowData?.[colField?.c_code || '']" fileClass="lowcode"
										return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }" :customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY" customFetchMethodName="FetchLowcodeFile" />
								</eui-col>
							</eui-row>
						</view>
						<view class="lowcode-page-sub-card-panel" v-for="(otherSubCardFormPanel, pIdx) in state?.subPanelsGridObj?.[oPanelGridGuid]">
							<view class="lowcode-page-sub-card-chead-wrap" v-if="otherSubCardFormPanel?.c_name" >
								<text class="lowcode-card-title item-text item-text-detail">{{ otherSubCardFormPanel?.c_name }}</text>
							</view>
							<view class="lowcode-title-line" v-if="otherSubCardFormPanel?.c_name" />
							<view class="lowcode-page-sub-card-cnt" v-if="otherSubCardFormPanel?.Components?.length">
								<eui-row v-for="(rowCols, fIdx) in otherSubCardFormPanel?.Components" :key="fIdx" class="lowcode-page-row-wrap">
									<eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
										<eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%" v-bind="state.subCellProps?.['other_sub'+(otherSubCardFormPanel?.c_guid || '')+idx+'_'+fIdx+'_'+cfIdx]" />
										<UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true" :autoUpload="false" serviceName="EnjoyMain" fileMediatype="image" :fileId="rowData?.[colField?.c_code || '']" fileClass="lowcode"
											return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }" :customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY" customFetchMethodName="FetchLowcodeFile" />
									</eui-col>
								</eui-row>
							</view>
						</view>
					</view>
				</eui-card>
				<eui-card v-if="(['1', '2'].includes(state?.otherPanelGridObj?.[oPanelGridGuid]?.c_type || '') && state.otherCellPropsAny?.[oPanelGridGuid] && state?.otherPanelGridObj?.[oPanelGridGuid]?.Components?.length) && state.otherPanelData?.[oPanelGridGuid]" :title="state?.otherPanelGridObj?.[oPanelGridGuid]?.c_name" hPadding="28" type="single" >
					<view class="lowcode-page-sub-card-chead-wrap" v-if="state?.otherPanelGridObj?.[oPanelGridGuid]?.ComponentsHeade?.length" >
						<eui-row v-for="(rowCols, fIdx) in state?.otherPanelGridObj?.[oPanelGridGuid]?.ComponentsHeade" :key="fIdx" class="lowcode-page-row-wrap">
							<eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
								<view class="lowcode-item-detail-view" >
									<text class="lowcode-card-title item-text item-text-detail">{{ getDetailCardTitle(state.otherPanelData?.[oPanelGridGuid], colField) }}</text>
								</view>
							</eui-col>
						</eui-row>
					</view>
					<view class="lowcode-title-line" v-if="state?.otherPanelGridObj?.[oPanelGridGuid]?.ComponentsHeade?.length" />
					<view class="lowcode-page-card-cnt" v-if="state?.otherPanelGridObj?.[oPanelGridGuid]?.Components?.length">
						<eui-row v-for="(rowCols, fIdx) in state?.otherPanelGridObj?.[oPanelGridGuid]?.Components" :key="fIdx" class="lowcode-page-row-wrap">
							<eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
								<eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%" v-bind="state.otherCellProps?.[oPanelGridGuid+'_form_'+fIdx+'_'+cfIdx]" />
								<UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true" :autoUpload="false" serviceName="EnjoyMain" fileMediatype="image" :fileId="state.otherPanelData?.[oPanelGridGuid]?.[colField?.c_code || '']" fileClass="lowcode"
									return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }" :customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY" customFetchMethodName="FetchLowcodeFile" />
							</eui-col>
						</eui-row>
					</view>
					<view class="lowcode-page-sub-card-panel" v-for="(otherSubCardFormPanel, pIdx) in state?.subPanelsGridObj?.[oPanelGridGuid]">
						<view class="lowcode-page-sub-card-chead-wrap" v-if="otherSubCardFormPanel?.c_name" >
							<text class="lowcode-card-title item-text item-text-detail">{{ otherSubCardFormPanel?.c_name }}</text>
						</view>
						<view class="lowcode-title-line" v-if="otherSubCardFormPanel?.c_name" />
						<view class="lowcode-page-sub-card-cnt" v-if="otherSubCardFormPanel?.Components?.length">
							<eui-row v-for="(rowCols, fIdx) in otherSubCardFormPanel?.Components" :key="fIdx" class="lowcode-page-row-wrap">
								<eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
									<eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%" v-bind="state.subCellProps?.['other_sub'+(otherSubCardFormPanel?.c_guid || '')+'form_'+fIdx+'_'+cfIdx]" />
									<UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true" :autoUpload="false" serviceName="EnjoyMain" fileMediatype="image" :fileId="state.otherPanelData?.[oPanelGridGuid]?.[colField?.c_code || '']" fileClass="lowcode"
										return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }" :customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY" customFetchMethodName="FetchLowcodeFile" />
								</eui-col>
							</eui-row>
						</view>
					</view>
				</eui-card>
			</view>
		</view>
		<view v-if="props?.parentType !== 'approveManger'" class="lowcode-page-btm-btns-wrap" >
			<eui-fab v-if="state.menusCFGMore?.length" class="lowcode-card-btm-btn-more" direction="vertical" :content="state.menusCFGMore" @trigger="handleMoreBtnClick" >
				<eui-uicons color="#888888" type="more-filled" size="30" />
			</eui-fab>
			<eui-button
				v-for="(mCFG, mIdx) in state.menusCFG"
				:key="mIdx"
				:type="getMenuBtnType(mCFG, mIdx)"
				:title="mCFG.menuTitle"
				:singleTag="mCFG.menuCode"
				:disabled="mBtnDis(mCFG)"
				@buttonClick="handleBtnClick"
				class="lowcode-page-btm-btn"
			/>
		</view>
		<eui-popup ref="popupAuditRef" class="lowcode-create-popup-wrap" background-color="#f8f8f8" type="bottom" :mask-click="false">
			<view class="lowcode-popup-content" >
				<view class="lowcode-popup-title"><view class="lowcode-popup-title-txt" >输入工作密码</view></view>
				<view class="lowcode-popup-default-content">
					<eui-card-input :value="'[' + store?.state?.value?.main?.loginInfo?.sUser + ']' + store?.state?.value?.main?.loginInfo?.sUserName" title="审核用户" type="textname" />
					<eui-card-input v-model="workPwd" title="工作密码" type="password" />
				</view>
			</view>
			<view class="lowcode-popup-bottom flex-1 flex">
				<eui-button type="max2" title="取消" singleTag="取消" @buttonClick="handleAuditClose"></eui-button>
				<eui-button type="max" title="确认" singleTag="确认" @buttonClick="handleAuditClose"></eui-button>
			</view>
		</eui-popup>
	</eui-background>
</template>

<script setup lang="ts" >
import { ref } from 'vue';
import { onLoad, onReady, onShow } from "@dcloudio/uni-app";
import store from '@/store';
import serviceTools from '@/common/service';
import useService from '@/hooks/useService';
import UploadFile from '@/components/UploadFile.vue';
import { initRdsDict, getRdsSysConfig } from '@/hooks/init';

import DynamicComponent from "../dynamicComponent/index.vue";
import useLowcodeSystemInfo from '../hooks/useSystemInfo';
import { formGridSort, lowcodeDefStatus } from '../utils';
import type { LowcodeBtnEvent, LowcodeGridRowColComponents, LowcodeMenuItemCFG, LowcodePage, LowcodePagePanel, LowcodePagePanelComponentItem, LowcodeRect } from '../interface';
import { EBillApproveStatus, EBillStatus, ECBillApproveStatus, ECBillStatus, EBillStatusTxt, LOWCODEDETAILSTATUSCONF, LOWCODERUNTIMEUNIQUEKEY, LOWCODEUNIQUEKEY, LOWCODERUNTIMEMOBILEUNIQUEKEY } from '../constant';
import type { MdBillRichDetailState, MdBillRichDetailProps, FetchMdBillRichDetailProxy, BillRichDetailFetchReq, BillRichDetailFetchRes, FetchRichDetailDataReq, FetchRichDetailDataRes } from './interface';
import useComponentProps from '../hooks/useComponentProps';
import useLowcodeMenuBtns from '../hooks/useLowcodeMenuBtns';

const props = defineProps<MdBillRichDetailProps>();

const workPwd = ref(""), workPwdBillId = ref(), popupAuditRef = ref();
const state = ref<MdBillRichDetailState>({}), popupRef = ref();

const service = useService({ prefix: "mainApi" }), serviceMBM = useService({ prefix: "mbmApi" });
const { getSystemInfo } = useLowcodeSystemInfo();
const { getComponentProps } = useComponentProps();
const { handleDeleteBill: handleDeleteBillHook, handleCancelBill: handleCancelBillHook, handleAuditBill: handleAuditBillHook, billDisabled: billDisabledHook, handleAuditValidate: handleAuditValidateHook } = useLowcodeMenuBtns();

const getNavTitle = () => props.billId ? ((props.billId || "") + "详情") : "新增";

const getMainCardTitle = () => {
	const rawIdVal = (props.billId || ''), cIdConf = state.value.cIdConf;
	if (cIdConf?.c_displayname_code) {
		const rawIdNameVal = state?.value?.mainFormData?.[cIdConf?.c_displayname_code] || "";
		return rawIdVal ? `[${rawIdVal}]${rawIdNameVal || ""}` : rawIdVal;
	}
	return rawIdVal;
}

const getMainStatusType = () => {
	if (state.value?.mainFormData?.c_status) {
		return (LOWCODEDETAILSTATUSCONF as any)[state.value?.mainFormData?.c_status];
	}
	return "primary_detail";
}

const getDetailCardTitle = (rowData: any, colField: LowcodePagePanelComponentItem) => {
	const rawIdVal = rowData?.[colField?.c_code || ""];
	if (colField?.c_displayname_code) {
		const rawIdNameVal = rowData?.[colField?.c_displayname_code] || "";
		return rawIdVal ? `[${rawIdVal}]${rawIdNameVal || ""}` : rawIdVal;
	}
	return rawIdVal;
};

const handleDeleteBill = async () => {
	const delRes = await handleDeleteBillHook({ BillId: state.value?.mainFormData?.c_id, UserNo: store?.state?.value?.main?.loginInfo?.sUser, ModuleCode: props.LowcodeGuid });
	delRes && uni.navigateTo({ url: `../index?LowcodeGuid=${props.LowcodeGuid}&LowcodeDetailGuid=${props.LowcodeDetailGuid}&moduleInfo=${props?.mdInfo}` });
};

const handleCancelBill = async () => {
	const cancelRes = await handleCancelBillHook({ BillId: state.value?.mainFormData?.c_id, UserNo: store?.state?.value?.main?.loginInfo?.sUser, ModuleCode: props.LowcodeGuid });
	cancelRes && uni.navigateTo({ url: `../index?LowcodeGuid=${props.LowcodeGuid}&LowcodeDetailGuid=${props.LowcodeDetailGuid}&moduleInfo=${props?.mdInfo}` });
};

const	handleAuditClose = async ({ singleTag }) => {
	if (singleTag === "取消") {
		return popupAuditRef.value?.close();
	}
	const userNo = store?.state?.value?.main?.loginInfo?.sUser;
	const userName = store?.state?.value?.main?.loginInfo?.sUserName;
	if (!workPwd.value) {
		return serviceTools.enjoyShowToast(`请录入[${userNo}]${userName}的审核密码！`);
	}

	const p = { InputAuditUserNo: userNo, MdCode: props.LowcodeGuid, WkPassword: workPwd.value };
	const validateAuditRes = await handleAuditValidateHook(p);
	if (validateAuditRes) {
		return serviceTools.enjoyShowToast(validateAuditRes);
	}
	const fetcRes = await handleAuditBillHook({ ...workPwdBillId.value });
	if (fetcRes) {
		fetchDetailData();
		popupAuditRef.value?.close();
	}
};

const handleBtnClick = async (btnEvent?: LowcodeBtnEvent) => {
	console.log("handleBtnClick ", btnEvent); // DeleteBill
	const mainFormData = state.value?.mainFormData;
	if (btnEvent?.singleTag === "DeleteBill") {
		const modalCnt = `您确认要删除当前单据吗？`;
		uni.showModal({ title: "提示", content: modalCnt, success: (res) => res.confirm && handleDeleteBill() });
		return;
	}
	if (btnEvent?.singleTag === "Cancel") {
		const modalCnt = `您确认要作废当前单据吗？`;
		uni.showModal({ title: "提示", content: modalCnt, success: (res) => res.confirm && handleCancelBill() });
		return;
	}
	if (btnEvent?.singleTag === "AUDIT") {
		if (!props?.billId) {
      serviceTools.enjoyShowToast("请先保存单据，再审核！");
      return false;
    }

		let asyncConfirmRes = false;
		const userNo = store?.state?.value?.main?.loginInfo?.sUser;
    const useWorkPass: string = await getRdsSysConfig("系统参数", "是否使用工作密码");

    if (useWorkPass === "确认提示") {
      const content = "请确认是否要审核当前单据？";
      asyncConfirmRes = await new Promise<boolean>((resolve, _) => uni.showModal({ title: "提示", content: content, success: (res) => res.confirm ? resolve(true) : resolve(false) }));
			if (!asyncConfirmRes) {
				return;
			}
			const fetcRes = await handleAuditBillHook({ BillId: props?.billId, UserNo: userNo, ModuleCode: props.LowcodeGuid });
			fetcRes && fetchDetailData();
    }

		if(useWorkPass === "是") {
			workPwdBillId.value = { BillId: props?.billId, UserNo: userNo, ModuleCode: props.LowcodeGuid };
			popupAuditRef.value?.open();
    }
		return false;
	}
	if (btnEvent?.singleTag === "APPROVE") {
		const appStatus = mainFormData?.c_approve_status || EBillApproveStatus.尚未审批;
		if ([EBillApproveStatus.正在审批, EBillApproveStatus.ApprovalProgress].includes(appStatus)) {
			uni.showLoading({ title: "查询中...", mask: true});
			const fetchReqTag = { Search: mainFormData?.c_id, Type: state.value?.mdInfo?.c_md_cname, StartDt: "", EndDt: "", SendUser: "", UserNo: store?.state?.value?.main?.loginInfo?.sUser };
			const fetchReq = { CurrentPage: 1, IsNotPage: false, PageCount: 1, PageSize: 10, RowsCount: 0, Tag: fetchReqTag };
			const fetchRes = await serviceMBM.request("管易通40审批", "GetApprovedListByBillType", fetchReq);
			const billAppInfo = fetchRes?.ReturnObject?.[0];
			if (billAppInfo) {
				uni.navigateTo({ url: '/pages/OaViews/Approve/ApproveStatus?item=' + JSON.stringify(billAppInfo) + '&tabIndex=2' });
			}
			if (!fetchRes || !billAppInfo) {
				uni.showModal({ title: "提示", content: "未查询到单据的审批信息！", success: res => {} });
			}
			return uni.hideLoading();
		}
		uni.navigateTo({ url: `/pages/ComDlgSelections/dlgSelApproveFlowSend?billId=${mainFormData?.c_id}&billKey=${mainFormData?.c_id}&mdCode=${props.LowcodeGuid}&mdCName=${state.value?.mdInfo?.c_md_cname}&billStatus=${mainFormData?.c_status}&appStatus=${mainFormData?.c_approve_status}&uniqueKey=${LOWCODERUNTIMEUNIQUEKEY}` }); // uniqueKey mainlowcodepcruntime
		return;
	}
	if (btnEvent?.singleTag === "EditBill") {
		const mdInfoEdit = typeof props?.mdInfo === "string" ? props?.mdInfo : (props?.mdInfo ? JSON.stringify(props?.mdInfo) : "");
		uni.navigateTo({ url: `../richDetail/edit?LowcodeGuid=${props.LowcodeGuid}&LowcodeDetailGuid=${props.LowcodeDetailGuid}&billId=${mainFormData?.c_id}&mdInfo=${mdInfoEdit}` });
		return;
	}
	popupRef.value?.open();
};

const handleMoreBtnClick = (...rest) => {
	console.log("handleMoreBtnClick ", rest);
}

const getMenuBtnType = (mCFG: LowcodeMenuItemCFG, mIdx: number) => {
	if (mIdx + 1 === state.value?.menusCFG?.length) {
		return "min";
	}
	return "min2";
};

const mBtnDis = (mCFG: LowcodeMenuItemCFG) => {
	let btnDis = false; // TODO 新建和审批，权限码里不包含这两个，要不要根据权限码判断禁用
	const mdLimit = state.value?.mdInfo?.c_limitcode || "R";	// c_limitcode: "RWSAOICUXDBP"
	const enableApprove = state.value.enableApprove;
	const c_status = state.value?.mainFormData?.c_status || EBillStatus.尚未审核;
	const appStatus = state.value?.mainFormData?.c_approve_status || EBillApproveStatus.尚未审批;

	if (mCFG.menuCode === "APPROVE") {
		const isNotApproved = c_status === EBillStatus.尚未审核 || c_status === ECBillStatus.NotApproved; // 尚未审核
    const isNotYetApproved = appStatus === EBillApproveStatus.NotYetApproved || appStatus === ECBillApproveStatus.NotYetApproved; // 尚未审批
    const isApprovalPassed = (appStatus === EBillApproveStatus.ApprovalPassed || appStatus === ECBillApproveStatus.ApprovalPassed); // 审批已通过
		btnDis = !(enableApprove ? (isNotApproved || isApprovalPassed) : (isNotYetApproved ? false : true));
		// if ([EBillApproveStatus.正在审批, EBillApproveStatus.ApprovalProgress].includes(appStatus)) {
		// 	btnDis = true;
		// }
		// if (!mdLimit.includes("E")) {
		// 	btnDis = true;
		// }
	}
	if (mCFG.menuCode === "DeleteBill" && !mdLimit.includes("D")) {
		btnDis = true; 	// 删单
	}
	if (mCFG.menuCode === "Cancel" && !mdLimit.includes("C")) {
		btnDis = true;	 // 作废
	}
	if (mCFG.menuCode === "AUDIT") {
		const isNotApproved = c_status === EBillStatus.尚未审核 || c_status === ECBillStatus.NotApproved; // 尚未审核
		const isApprovalPassed = (appStatus === EBillApproveStatus.ApprovalPassed || appStatus === ECBillApproveStatus.ApprovalPassed); // 审批已通过
		const isApprovving = (appStatus === EBillApproveStatus.ApprovalProgress || appStatus === ECBillApproveStatus.ApprovalProgress); // 正在审批
		btnDis = !(isNotApproved && (enableApprove ? isApprovalPassed : true)) || isApprovving;
		if (!mdLimit.includes("A")) {
			btnDis = true; 	 // 审核
		}
	}
	// if (mCFG.menuCode === "NEWBILL" && !mdLimit.includes("D")) {
	// 	btnDis = true;	 // 新单
	// }
	return btnDis;
};

const handleMenuBtns = () => {
	const filterMenus = state.value?.c_menuCFG?.filter(m => m.menuCode !== "EditBill");
	const billDisabled = false; // billDisabledHook({ approving: props?.parentType === "approveManger", mdLimit: state.value?.mdInfo?.c_limitcode || "R", mainData: state.value?.mainFormData });

	if (filterMenus && Array.isArray(filterMenus) && filterMenus.length) {
		const splitIdx= billDisabled ? 4 : 3;
		const cacheMenusCFG = filterMenus.slice(0, splitIdx);
		state.value.menusCFGMore = filterMenus.slice(splitIdx)?.map(m => ({ text: m.menuTitle || "" }));

		if (!billDisabled) {
			cacheMenusCFG?.push({
				actionCFGTitle: null,
				enableActionCFG: null,
				handleCode: "EditBill",
				isEnable: "1",
				menuAction: null,
				menuCode: "EditBill",
				menuTitle: "修改",
			} as any);
		}
		state.value.menusCFG = cacheMenusCFG
	}
};

const getMainSubCardFormPanels = () => {
	const mainSubCardFormGuid = state.value?.mainFormPanel?.c_guid;
	const mainSubCardFormPanels = state.value?.subPanelsGridObj?.[mainSubCardFormGuid  || ""];
	return mainSubCardFormPanels;
}

const getMainCellProps = async () => {
	if (!state.value?.mainFormData || !state.value?.mainFormPanelGrid?.Components?.length) {
		return;
	}
	for (let fIdx = 0; fIdx < state.value?.mainFormPanelGrid?.Components?.length; fIdx++) {
		const rowCols = state.value?.mainFormPanelGrid?.Components[fIdx];
		for (let cfIdx = 0; cfIdx < rowCols?.length; cfIdx++) {
			if (!state.value?.mainCellProps) {
				state.value.mainCellProps = {};
			}
			const colField = rowCols[cfIdx];
			state.value.mainCellProps['main_'+fIdx+'_'+cfIdx] = await getComponentProps({ componentType: 'EuiText', confObject: colField, dataObject: state.value?.mainFormData });
		}
	}
};

const fillOtherCellProps = async (pGridInfo: LowcodeGridRowColComponents, pGuid: string, prefix: string, allData: { [key: string]: any }) => {
  if (!pGridInfo || !pGridInfo?.Components) {
    return;
  }
	if (!state.value.otherCellPropsAny) {
		state.value.otherCellPropsAny = {};
	}
	state.value.otherCellPropsAny[pGuid] = true;
  for (let fIdx = 0; fIdx < pGridInfo?.Components?.length; fIdx++) {
    const rowCols = pGridInfo?.Components[fIdx];
    for (let cfIdx = 0; cfIdx < rowCols?.length; cfIdx++) {
      if (!state.value?.otherCellProps) {
        state.value.otherCellProps = {};
      }
      const colField = rowCols[cfIdx];
      state.value.otherCellProps[prefix+'_'+fIdx+'_'+cfIdx] = await getComponentProps({ componentType: 'EuiText', confObject: colField, dataObject: allData, parentSrc: "3" });
    }
  }
};

const getOtherCellProps = async () => {
  const otherPanelGuidAry = Object.keys(state.value?.otherPanelGridObj || {});
	// if (!otherPanelGuidAry?.length) {
	if (!Object.keys(state.value?.otherPanelData || {}).length || !otherPanelGuidAry?.length) {
		return;
	}
  for (let pidx = 0; pidx < otherPanelGuidAry.length; pidx++) {
    const pGuid = otherPanelGuidAry[pidx];
    const guidPanelData = state.value.otherPanelData?.[pGuid];
    const pGridInfo = state.value?.otherPanelGridObj?.[pGuid];

    if (!pGridInfo || !pGridInfo?.Components) {
      continue;
    }

    if (["1", "2"].includes(pGridInfo?.c_type || "")) {   // 容器类型，1:普通表单、2:卡片表单、3、数据表格、4：页签。 暂不支持4页签
      fillOtherCellProps(pGridInfo, pGuid, pGuid+'_form', (Array.isArray(guidPanelData) ? guidPanelData?.[0] : guidPanelData) || {});
    }

		if (["3"].includes(pGridInfo?.c_type || "")) {
			for (let idx = 0; idx < (guidPanelData || [{}])?.length; idx++) {
				const rowData = guidPanelData?.[idx];
				fillOtherCellProps(pGridInfo, pGuid, pGuid+'_'+idx, rowData || {});
			}
		}
  }
};

const fillSubCellProps = async (subKey: string, subCardFormPanel?: LowcodeGridRowColComponents, formData?: { [key: string]: any }, parentSrc?: string) => {
	if (!formData || !subCardFormPanel?.Components?.length) {
		return;
	}
	for (let fIdx = 0; fIdx < subCardFormPanel?.Components?.length; fIdx++) {
		const rowCols = subCardFormPanel?.Components[fIdx];
		for (let cfIdx = 0; cfIdx < rowCols?.length; cfIdx++) {
			if (!state.value?.subCellProps) {
				state.value.subCellProps = {};
			}
			const colField = rowCols[cfIdx];
			state.value.subCellProps[subKey+fIdx+'_'+cfIdx] = await getComponentProps({ componentType: 'EuiText', confObject: colField, dataObject: formData, parentSrc });
		}
	}
}

const getSubCardCellProps = async () => {
	const mainSubCardFormPanels = getMainSubCardFormPanels();
	for (let i = 0; i < (mainSubCardFormPanels?.length || 0); i++) {
		const mainSubCardFormPanel = mainSubCardFormPanels?.[i];
		const subKey = "main_sub" + (mainSubCardFormPanel?.c_guid || "");
		await fillSubCellProps(subKey, mainSubCardFormPanel, state.value?.mainFormData);
	}

  const subPanelGuidAty = Object.keys(state.value?.subPanelsGridObj || {});
  if (!subPanelGuidAty?.length) {
    return;
  }
  for (let pIdx = 0; pIdx < subPanelGuidAty?.length; pIdx++) {
    const pGuid = subPanelGuidAty[pIdx];
    if (state.value?.mainFormPanel?.c_guid === pGuid) {
      continue;
    }
    const otherSubCardFormPanels = state.value?.subPanelsGridObj?.[pGuid];
    const subPanelData = state.value?.otherPanelData?.[pGuid];
    const parentPanelGridInfo = state.value?.otherPanelGridObj?.[pGuid];
    const parentContainerType = parentPanelGridInfo?.c_type || "";

    if (["1", "2"].includes(parentContainerType)) {   // 容器类型，1:普通表单、2:卡片表单、3、数据表格、4：页签。 暂不支持4页签
      for (let i = 0; i < (otherSubCardFormPanels?.length || 0); i++) {
        const otherSubCardFormPanel = otherSubCardFormPanels?.[i];
        const subKey = "other_sub" + (otherSubCardFormPanel?.c_guid || "") + "form" + "_";
				const oSubFormData = (Array.isArray(subPanelData) ? subPanelData?.[0] : subPanelData) || {};
        await fillSubCellProps(subKey, otherSubCardFormPanel, oSubFormData, parentContainerType);
      }
    }

		if (["3"].includes(parentContainerType)) {
			for (let rowIdx = 0; rowIdx < ((subPanelData || [{}])?.length || 0); rowIdx++) {
				const rowData = subPanelData?.[rowIdx];
				for (let i = 0; i < (otherSubCardFormPanels?.length || 0); i++) {
					const otherSubCardFormPanel = otherSubCardFormPanels?.[i];
					const subKey = "other_sub" + (otherSubCardFormPanel?.c_guid || "") + rowIdx + "_";
					await fillSubCellProps(subKey, otherSubCardFormPanel, rowData, parentContainerType);
				}
			}
		}
  }
};

const initData = async (fetchProxy?: FetchMdBillRichDetailProxy) => {
	await getMainCellProps();
	await getOtherCellProps();
	await getSubCardCellProps();

	if (fetchProxy?.isOnLoad) {
		const userInfoPage = uni.createSelectorQuery().select(".lowcode-nav-bg-wrap");
		userInfoPage.boundingClientRect(rect => {
			(state.value.navWrapRect = (rect as LowcodeRect));
			const maxBasicH = state.value.otherPanelData?.length ? (state.value.systemInfo?.windowHeight / 2) : state.value.systemInfo?.windowHeight;
			const maxDiffH = state.value.otherPanelData?.length ? 100 : 130;
			const maxHeight = Math.floor(maxBasicH - (state.value?.navWrapRect?.height || 0) - maxDiffH);
			const basicPageH = Math.floor(state.value.systemInfo?.windowHeight - (state.value?.navWrapRect?.height || 0) - 120);
			if (props?.parentType === "approveManger") {
				state.value.approveStyle = { height: basicPageH + "px" };
			}
			state.value.createPopupStyle = { height: Math.floor(basicPageH * 0.9) + "px" };
			state.value.mainCardStyle = { 'max-height': maxHeight + 'px', 'overflow-y': 'auto' };
		}).exec();
	}
  console.log("after initData ", state.value);
};

const fetchDetailData = async (fetchProxy?: FetchMdBillRichDetailProxy) => {
	uni.showLoading({ title: "查询中...", mask: true});
	const fetchReq = { BillId: props.billId };
	const fetchReqProxy = { ModuleCode: props.LowcodeGuid };
	const fetchRes = await service.request<FetchRichDetailDataReq, FetchRichDetailDataRes>(LOWCODERUNTIMEMOBILEUNIQUEKEY, "EnjoyBillQuery", fetchReq, "", "", fetchReqProxy);
	uni.hideLoading();
	if (!fetchRes) {
		return;
	}
	Object.keys(fetchRes || {})?.forEach((k, kIdx) => {
		const kData = Array.isArray(fetchRes[k]) ? fetchRes[k]?.map(r => ({ ...r, ...lowcodeDefStatus(r) })) : ({ ...fetchRes[k], ...lowcodeDefStatus(fetchRes[k]) });
		if (k === "ds") {
			state.value.mainFormData = (Array.isArray(kData) ? kData[0] : kData) || {};
			return;
		}
		const pGuidAry = Object.keys(state.value.otherPanelObj || {});
		const pGuid = pGuidAry[kIdx - 1];
		if (!state.value?.otherPanelData) {
			state.value.otherPanelData = {};
		}
		state.value.otherPanelData[pGuid] = kData;
	});
	handleMenuBtns();
	await initData(fetchProxy);
};

const handleLowCodePage = async (pageConf?: LowcodePage) => {
	const menuCFG = pageConf?.c_menuCFG || null;
	const filterMenus = menuCFG?.menus?.filter(m => !["AddRow", "DeleteRow", "SaveBill"].includes(m.menuCode || ""));
	state.value.c_menuCFG = filterMenus;
	handleMenuBtns();

	const enableApprove = await getRdsSysConfig("单据是否审批", state.value?.mdInfo?.c_md_cname) === "是";
	state.value.enableApprove = enableApprove;

	const topPanels: LowcodePagePanel[] = [], subPanels: { [key:string]: LowcodePagePanel } = {};
	pageConf?.Panels?.forEach(p => {
		if (p?.c_ppanel_guid) {
			if (!state.value?.subPanelsGridObj) {
				state.value.subPanelsGridObj = {};
			}
			if (!Array.isArray(state.value?.subPanelsGridObj[p.c_ppanel_guid])) {
				state.value.subPanelsGridObj[p.c_ppanel_guid] = [];
			}
			state.value.subPanelsGridObj[p.c_ppanel_guid].push(({ ...p, ...formGridSort(p?.Components) }) as LowcodeGridRowColComponents);
		} else {
			topPanels.push(p);
		}
	});

	state.value.cIdConf = topPanels?.[0]?.Components?.find(c => c.c_code === "c_id");
  state.value.mainFormPanel = ({ ...topPanels?.[0] });
	state.value.mainFormPanelGrid = ({ ...topPanels?.[0], ...formGridSort(topPanels?.[0]?.Components) }) as LowcodeGridRowColComponents;
	// state.value.mainComponents = topPanels?.[0]?.Components;

	topPanels?.forEach((panel, pIdx) => {
		if (pIdx === 0 || !panel?.c_guid) {
			return;
		}
    if (!state?.value?.otherPanelObj) {
			state.value.otherPanelObj = {};
		}
    state.value.otherPanelObj[panel.c_guid] = ({ ...panel });
		if (!state?.value?.otherPanelGridObj) {
			state.value.otherPanelGridObj = {};
		}
    state.value.otherPanelGridObj[panel.c_guid] = ({ ...panel, ...formGridSort(panel?.Components) }) as LowcodeGridRowColComponents;
	});
};

const fetchDetailPage = async (fetchProxy?: FetchMdBillRichDetailProxy) => {
	const fetchReqProxy = { ModuleCode: props.LowcodeGuid };
	const fetchReq = { LowcodeGuid: props.LowcodeGuid || "", LowcodeDetailGuid: props.LowcodeDetailGuid || "" };
	uni.showLoading({ title: "查询中...", mask: true});
	const fetchRes = await service.request<BillRichDetailFetchReq, BillRichDetailFetchRes>(LOWCODEUNIQUEKEY, "FindMobileRuntimeDetailPage", fetchReq, "", "", fetchReqProxy);
	uni.hideLoading();
	if (fetchRes !== undefined) {
		await handleLowCodePage(fetchRes?.LowcodePage);
		await fetchDetailData(fetchProxy);
	}
	state.value.lowcodeInfo = fetchRes?.Lowcode;
};

const handleSystemInfo = () => {
	const systemInfo = getSystemInfo();
	state.value.systemInfo = systemInfo;
};

const navBarClickLeft = () => {
	let naviBackNum = 1;
	const pages = getCurrentPages?.();
	const pagesReverse = [...pages].reverse();
	const filterPages = ["pages/MainViews/lowcode/richDetail/index", "pages/MainViews/lowcode/richDetail/edit"];
	const reverseIdx = pagesReverse?.findIndex(r => !filterPages.includes(r?.route || ""));
	if (reverseIdx >= 0) {
		naviBackNum = reverseIdx;
	}
	console.log("navBarClickLeft pages", pages);
	uni.navigateBack({ delta: naviBackNum });
};


defineExpose({
  navBarClickLeft
});

onLoad(async (proxy) => {
	console.log("onLoad proxy ", proxy);
	uni.$on("RefreshPage", fetchDetailData);
  state.value.mdInfo = props.mdInfo ? JSON.parse(props.mdInfo || "") : null;
	await initRdsDict();
	handleSystemInfo();
	fetchDetailPage({ isOnLoad: true });
});
</script>

<style scoped lang="scss">
@import '@/main.scss';
@import "../index.scss";
@import "./index.scss";
</style>
